package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.constant.Constant;
import com.bdqn.pojo.PageSupport;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SupplierService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/**/supplier")
public class SupplierController {
    private Logger logger = Logger.getLogger(SupplierController.class);

    @Resource
    private SupplierService supplierService;

    @RequestMapping("/list")
    public String getList( Model model, HttpServletRequest request,@RequestParam(required = false) String supCode, @RequestParam(required = false) String supName,@RequestParam(defaultValue = "1") Integer pageIndex){
        logger.info("进入supplier获取list方法");
        List<Supplier> supplierList = null;
        try{
            //设置页面容量
            int pageSize = Constant.pageSize;
            //总数量(表)
            int totalCount = supplierService.getSupplierCount(supCode,supName);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            supplierList = supplierService.getSupplierList(supCode,supName,pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount", pages.getTotalCount());
            model.addAttribute("currentPageNo",pages.getCurrentPageNo());
            model.addAttribute("querySupCode",supCode);
            model.addAttribute("querySupName",supName);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
        }
        return "supplier/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){

        return "supplier/add";
    }

    @PostMapping("/add")
    public String add(Model model, Supplier supplier, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs){
        // 企业营业执照路径
        String companyLicPic = null;
        // 组织机构代码证路径
        String orgCodePic = null;
        // 错误信息
        String errorInfo = null;
        boolean flag = true;
        // 文件的存储位置
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件的存储路径:" + path);
        for (int i = 0; i < attachs.length; i++) {
            // 获取单独的上传照片对象
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    // 异常信息
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename(); // 原来的文件名
                logger.info("原来的文件名:" + oldFileName); // 原文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName); // 使用FilenameUtils工具类提取文件名的后缀
                logger.debug("原文件后缀:" + prefix);
                int filesize = 5000000;
                logger.debug("上传文件大小:" + attach.getSize());
                if (attach.getSize() > filesize) { // 上传大小不得超过500 KB
                    request.setAttribute(errorInfo, " * 上传大小不得超过 500 KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    // 文件名的重组:系统的时间戳+随机数+_Personal.+原来的后缀
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + "_Personal." + prefix;
                    File targerFile = new File(path);
                    // 判断路径下的文件是否存在
                    if (!targerFile.exists()) {
                        // 不存在则创建
                        targerFile.mkdirs();
                    }
                    // 保存

                    try {
                        // 文件传输
                        attach.transferTo(new File(targerFile, fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传失败!");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPic = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else {
                        orgCodePic = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("companyLicPic" + companyLicPic);
                    logger.debug("orgCodePic" + oldFileName);
                } else {
                    request.setAttribute("errorInfo", " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            supplier.setCreatedUserId(Long.valueOf(Integer.valueOf(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId())));
            supplier.setCreatedTime(new Date());
            supplier.setCompanyLicPicPath(companyLicPic);
            supplier.setOrgCodePicPath(orgCodePic);
            if (supplierService.getSupplierAdd(supplier)>0) {
                return "redirect:/supplier/list";
            }
            supplier.setCreatedUserId(Long.valueOf(Integer.valueOf(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId())));
            if (supplierService.getSupplierAdd(supplier)>0) {
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }

    /**
     * 查看视图
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view/{id}")
    //@GetMapping("/{id}")
    //@GetMapping("/{id}/view")
    public String view(@PathVariable String id, Model model) {
        logger.debug("根据Id查询用户详情" + id + "\n");
        Supplier supplier = supplierService.getSupplierId(id);
        model.addAttribute(supplier);
        return "supplier/view";
    }

    //修改信息
    @RequestMapping("/toUpdate/{supId}")
    public String toUpdate(@PathVariable String supId,Model model){
        Supplier supplier = supplierService.getSupplierId(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }

    @RequestMapping("/update")
    public String update(Supplier supplier,HttpSession session){
        logger.debug("修改供货商信息");
        supplier.setUpdatedUserId(Long.valueOf(((SysUser) session.getAttribute(Constant.USER_SESSION)).getId()));
        supplier.setUpdatedTime(new Date());
        logger.debug("供应商更新后数据：" + supplier);
        if (supplierService.getUpdate(supplier)){
            return "redirect:supplier/list";
        }
        return "supplier/update";
    }

    @ResponseBody
    @RequestMapping("/del/{id}")
    public Object del(@PathVariable String id){
        logger.info("进入供货商删除方法");
        HashMap<String,Object> resultMap = new HashMap<String,Object>();
        logger.info("删除供货商的ID：" + id);
        if (supplierService.delSupplier(Long.valueOf(id))){
            resultMap.put("delResult","true");
        }else{
            resultMap.put("delResult","false");
        }
        return JSON.toJSONString(resultMap);
    }
}
